package com.uu;

import java.util.Random;

public class ReversiblePermutationShuffleUtil {

    /**
     * 基于密钥生成固定随机数生成器
     */
    private static Random getSeededRandom(String key) {
        long seed = key.hashCode();
        return new Random(seed);
    }

    /**
     * 生成置换序列
     */
    private static int[] generatePermutation(int length, Random random) {
        int[] permutation = new int[length];
        for (int i = 0; i < length; i++) {
            permutation[i] = i;
        }

        // Fisher-Yates洗牌算法
        for (int i = length - 1; i > 0; i--) {
            int j = random.nextInt(i + 1);
            int temp = permutation[i];
            permutation[i] = permutation[j];
            permutation[j] = temp;
        }

        return permutation;
    }

    /**
     * 生成逆置换序列
     */
    private static int[] generateInversePermutation(int[] permutation) {
        int length = permutation.length;
        int[] inverse = new int[length];
        for (int i = 0; i < length; i++) {
            inverse[permutation[i]] = i;
        }
        return inverse;
    }

    /**
     * 乱序 - 字符位置置换
     */
    public static String shuffle(String text, String key) {
        if (text == null || text.length() <= 1) {
            return text;
        }

        Random random = getSeededRandom(key);
        int length = text.length();
        int[] permutation = generatePermutation(length, random);

        char[] chars = text.toCharArray();
        char[] shuffled = new char[length];

        for (int i = 0; i < length; i++) {
            shuffled[i] = chars[permutation[i]];
        }

        return new String(shuffled);
    }

    /**
     * 恢复 - 逆置换
     */
    public static String restore(String shuffledText, String key) {
        if (shuffledText == null || shuffledText.length() <= 1) {
            return shuffledText;
        }

        Random random = getSeededRandom(key);
        int length = shuffledText.length();
        int[] permutation = generatePermutation(length, random);
        int[] inversePermutation = generateInversePermutation(permutation);

        char[] shuffledChars = shuffledText.toCharArray();
        char[] restored = new char[length];

        for (int i = 0; i < length; i++) {
            restored[i] = shuffledChars[inversePermutation[i]];
        }
        return new String(restored);
    }

    public static void main(String[] args) {
        String text = "uni_183_moa,eceb4e4320829c9b01d38fa103f754e7,bc54f253-f8b5-4363-aba7-6b59275fb5ed";
        System.out.println(text);
        String key = "myKey";
        String result = ReversiblePermutationShuffleUtil.shuffle(text, key);
        System.out.println(result);

        String restored = ReversiblePermutationShuffleUtil.restore(result, key);
        System.out.println(restored);
    }
}
